package com.shouhuobao.samecity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.collectplus.express.BaseActivity2;
import com.collectplus.express.R;
import com.collectplus.express.logic.AppConfig;
import com.collectplus.express.logic.AppHttp;
import com.collectplus.express.logic.AppResult;
import com.collectplus.express.logic.JSON;
import com.collectplus.express.logic.MsgID;
import com.collectplus.express.model.SameCityHistoryBean;
import com.collectplus.express.tools.TextWatcherExt;
import com.shouhuobao.bhi.loc.BaiduLocationService;

import droid.frame.utils.Android;

/**
 * @author 李澄锋<br>
 * 2018/6/27
 */
public class SameCityBaseActivityWithSearch extends BaseActivity2 implements View.OnClickListener {

    private View mTitleLayout;// 顶部TitleLayout
    private EditText mEditInput;
    protected TextView mSearchOrCancel;// 搜索按钮(搜索状态显示取消)
    protected ListView mListView2;// 搜索结果列表
    /**
     * 只有点击搜索按钮才收起键盘 (通过联想不收起键盘)
     */
    private boolean autoSearch = true;

    protected String mCurrentCityName = "";//城市名字

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        showLoadingDialog("定位中");
        Intent intent = new Intent();
        intent.setClass(getContext(), BaiduLocationService.class);
        startService(intent);
    }

    @Override
    protected void findViewById() {
        super.findViewById();
        mTitleLayout = findViewById(R.id.app_title_layout);
        mListView2 = (ListView) findViewById(R.id.listview2);

        mSearchOrCancel = (TextView) findViewById(R.id.visit_search_submit);
        mSearchOrCancel.setOnClickListener(this);

        mEditInput = (EditText) findViewById(R.id.visit_edit_input);
        mEditInput.clearFocus();
        mEditInput.setFocusable(false);
        mEditInput.setFocusableInTouchMode(false);
        mEditInput.setOnClickListener(this);
        mEditInput.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        mEditInput.addTextChangedListener(new TextWatcherExt() {
            private Handler handler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    if (msg.what == 99999) {
                        String keywords = mEditInput.getText().toString();
                        if (isEmpty(keywords)) {
                            // ignore
                        } else {
                            autoSearch = true;
                            if (isNotEmpty(mCurrentCityName)) {
//                                showLoadingDialog(null);
                                AppHttp.getInstance().serachaddressStation(mCurrentCityName, keywords);
                            }
                        }
                    }
                }
            };


            @Override
            public void afterTextChanged(Editable s) {
                handler.removeMessages(99999);
                handler.sendEmptyMessageDelayed(99999, 300);
            }
        });
        mEditInput.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                //
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    String keywords = mEditInput.getText().toString();
                    if (isEmpty(keywords)) {
                        // ignore
                    } else {
                        autoSearch = false;
                        if (isNotEmpty(mCurrentCityName)) {
//                            showLoadingDialog(null);
                            AppHttp.getInstance().serachaddressStation(mCurrentCityName, keywords);
                        }
                    }
                    return true;
                }
                return false;
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            // 搜索框
            case R.id.visit_edit_input:
                // 非"搜索"状态下点击搜索框--切换到搜索状态
                if (mSearchOrCancel.getTag() == null) {
                    mSearchOrCancel.setVisibility(View.VISIBLE);
                    mSearchOrCancel.setTag("");//
                    mSearchOrCancel.setText("取消");
                    mTitleLayout.setVisibility(View.GONE);
                    mListView2.setVisibility(View.VISIBLE);
                    getHandler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mEditInput.setFocusable(true);
                            mEditInput.setFocusableInTouchMode(true);
                            mEditInput.requestFocus();
                            Android.showSoftInput(getContext(), mEditInput);
                        }
                    }, 200);
                } else {
                    // 搜索状态点击, 不作处理
                }
                break;
            // 搜索
            case R.id.visit_search_submit:
                if (mSearchOrCancel.getTag() == null) {
                    // 非搜索状态, 点击搜索按钮不做处理
                } else {
                    // 取消
                    mSearchOrCancel.setTag(null);//
                    mSearchOrCancel.setText("搜索");
                    mSearchOrCancel.setVisibility(View.GONE);
                    mTitleLayout.setVisibility(View.VISIBLE);
                    mListView2.setVisibility(View.GONE);
                    mListView2.setAdapter(null);
                    getHandler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mEditInput.setFocusable(false);
                            mEditInput.setFocusableInTouchMode(false);
                            mEditInput.clearFocus();
                            Android.hideSoftInput(getContext());
                        }
                    }, 200);
                }
                break;
        }
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case MsgID.location_baidu:
                cancelLoadingDialog();
                BDLocation mBdLocation = (BDLocation) msg.obj;
                if (mBdLocation != null) {
                    if (AppConfig.isOtherCity != 0) {
                        mCurrentCityName = AppConfig.getCityName();
                    } else {
                        mCurrentCityName = mBdLocation.getCity();
                    }
                } else {
                    showToast("定位失败");
                }
                return false;
            //根据关键字搜索附近驿站
            case MsgID.serach_address_for_keywords:
                cancelLoadingDialog();
                final AppResult<SameCityHistoryBean> result = JSON.parseList(msg.obj, SameCityHistoryBean.class);
                if (result.isSuccess()) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (result.getResultList() != null && result.getResultList().size() > 0) {
                                SameCityAddressAdapter mAdapter = new SameCityAddressAdapter(result.getResultList(), getContext());
                                mListView2.setAdapter(mAdapter);

                                if (autoSearch) {
                                    // 通过联想搜索 不收键盘
                                } else {// 点击搜索 收起键盘
//                                    getHandler().postDelayed(new Runnable() {
//                                        @Override
//                                        public void run() {
//                                            Android.hideSoftInput(getContext());
//                                        }
//                                    }, 200);
                                }
                            } else {
                                SameCityAddressAdapter mAdapter = new SameCityAddressAdapter(null, getContext());
                                mListView2.setAdapter(mAdapter);
                                showToast("搜索结果为空");
                            }
                        }

                    });

                }
                return false;
            default:
                return super.handleMessage(msg);
        }
    }
}
